jQuery.validator.addMethod("checkBalance", function(value,element) {
    var  balance=0;
    return this.optional(element) || value>balance;
}, $.validator.format("数值必须大于0"));
//必输字段 面额
$("#amount").blur(function(){
    if(this.value != 0 ){
        $("#message").css('display','none');
    }else{
        $(this).next("span").html("为必填字段");
    }
});
//必输字段 主题名称
$("#topicName").blur(function(){
    if(this.value != 0 ){
        $("#message0").css('display','none');
    }else{
        $(this).next("span").html("为必填字段");
    }
});
//必输字段 数量
$("#totalCount").blur(function(){
    if(this.value != 0 ){
        $("#message2").css('display','none');
    }else{
        $(this).next("span").html("为必填字段");
    }
});
//spu sku 文本框校验
function testShuRu(a)
{
    var patt1=new RegExp("^[;.a-zA-Z0-9\u0020]*$");
    if(!patt1.test(a)){
        $.Huimodalalert('请按商品编码组成规则：输入字母、数字、英文状态下分号、点',2000);
        // $("#spuText").val().replace(/[^;.a-zA-Z0-9]/g, "");
    }
}

function getTopicType() {
    if($("#topicType").val()==20){
        $("#orderMoney").html("单笔订单运费金额满");
        $("#applRange").hide();
        $("#applCate").hide();
        $("#cateLevel").hide();
        $("#tab_goods").hide();
    }else{
        $("#orderMoney").html("单笔订单适用商品金额满");
        $("#applRange").show();
        $("#applCate").show();
        $("#cateLevel").show();
        $("#tab_goods").show();
    }
}

var applPaidType ='';
$("input[name='paidType']").change(function() {
    applPaidType ='';
    var groupCheckbox =  $("input[name='paidType']");
    for(var i=0;i<groupCheckbox.length;i++){
        if(groupCheckbox[i].checked){
            var val =groupCheckbox[i].value;
            if(i==groupCheckbox.length-1){
                applPaidType += val ;
            }else{
                applPaidType += val +',';
            }
        }
        if(groupCheckbox[i].checked==false){
            document.getElementById("applPaidType0").checked = false;
        }
    }
    console.log(applPaidType);

});

function HashMap(){this.map = {};}
HashMap.prototype = {
    put :function(key, value){ this.map[key] = value;},
    get : function(key){
        if(this.map.hasOwnProperty(key)){ return this.map[key];}
        return null;
    },
    remove : function(key){
        if(this.map.hasOwnProperty(key)){ return delete this.map[key];}
        return false;
    },
    removeAll:  function(){this.map = {};},
    keySet : function(){
        var _keys = [];
        for(var i in this.map){
            _keys.push(i);
        }
        return _keys;
    }
};

HashMap.prototype.constructor = HashMap;
var mapList = new HashMap();
var mapList1 = new HashMap();

var flag = 0;
var flag2 = 0;

var count = 0;//默认 没有
function check_pay(){
    if(count==0){
        document.getElementById("applPaidType0").checked=true;
        $("input[name='paidType']").prop("checked",true);
        count = 1;
        applPaidType = document.getElementById("applPaidType0").value;
        console.log(applPaidType);
    }else if(count==1){
        document.getElementById("applPaidType0").checked=false;
        $("input[name='paidType']").prop("checked",false);
        count = 0;
        applPaidType = '';
    }
}

var checkLength = function(dom, maxLength){
    var l = 0;
    for(var i=0; i<dom.value.length; i++) {
        if (/[\u4e00-\u9fa5]/.test(dom.value[i])) {
            l+=2;
        } else {
            l++;
        }
        if (l > maxLength) {
            dom.value = dom.value.substr(0,i);
            break;
        }
    }
};


function putDataToPage() {
    /*渲染spu sku值到页面*/
    var formData = new FormData();
    formData.append("topicId", 100);
    formData.append("applProduct", 1);
    if($("#tabbox1")[0].style.display == "block"){
        formData.append('type',1);
    }
    else if($("#tabbox2")[0].style.display == "block"){
        formData.append('type',2);
    }
    formData.append('spulist',$('#spuText').val());
    formData.append('skulist',$('#skuText').val());
    formData.append('spulist1',$('#spuText1').val());
    formData.append('skulist1',$('#skuText1').val());
    formData.append('file', $("#fileUp")[0].files[0]);
    // console.log($("#fileUp")[0].value)
    $.ajax({
        url: root.couponInter.coupon_excelImportProduct,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data)
            if(data.code==1){
                $.Huimodalalert(data.message,2000);
            }
            var spuStr = "";
            var skuStr = "";
            var oldSpuStr = $("#spuText").val();
            var oldSkuStr = $('#skuText').val();
            var oldSpuStr1 = $("#spuText1").val();
            var oldSkuStr1 = $('#skuText1').val();
            for (var i = 0; i < data.successList.length; i++) {
                if (i < data.successList.length - 1) {
                    if (data.successList[i].spuCode!=null){
                        spuStr = data.successList[i].spuCode+ "  ;  "+spuStr;
                    }
                    if (data.successList[i].skuCode!=null){
                        skuStr = data.successList[i].skuCode + "  ;  "+skuStr;
                    }
                }
                else if (i == data.successList.length - 1) {
                    if (data.successList[i].spuCode!=null){
                        spuStr += data.successList[i].spuCode;
                    }
                    if (data.successList[i].skuCode!=null){
                        skuStr += data.successList[i].skuCode;
                    }
                }
            }

            // if (skuStr.lastIndexOf(";")==(skuStr.length-1)){
            //     $("#skuText").val(skuStr.substring(0,skuStr.length-1));
            // }
            if($("#tabbox1")[0].style.display == "block"){
                if($("#spuText").val()==''){
                    $("#spuText").val(spuStr);
                }
                else{
                    if(spuStr!=''){
                        $("#spuText").val(oldSpuStr+';'+spuStr);
                    }
                }
                if($("#skuText").val()==''){
                    $("#skuText").val(skuStr);
                }
                else{
                    if(skuStr!=''){
                        console.log('oldSkuStr'+':'+oldSkuStr);
                        $("#skuText").val(oldSkuStr+';'+skuStr);
                    }
                }
            }
            else if($("#tabbox2")[0].style.display == "block"){
                if($("#spuText1").val()==''){
                    $("#spuText1").val(spuStr);
                }
                else{
                    if(spuStr!=''){
                        $("#spuText1").val(oldSpuStr+';'+spuStr);
                    }
                }
                if($("#skuText1").val()==''){
                    $("#skuText1").val(skuStr);
                }
                else{
                    if(skuStr!=''){
                        console.log('oldSkuStr'+':'+oldSkuStr);
                        $("#skuText1").val(oldSkuStr+';'+skuStr);
                    }
                }
            }
            $("#fileUp")[0].value = ""

            var p=[];
            var k=[];
            var u=[];
            var o=[];
            var failSpu=[];
            var failSku=[];
            for(var i=0;i<data.successList.length;i++){
                var j=i+1;
                if(data.successList[i].spuCode==null){
                    p.push(j);
                }
                if(data.successList[i].skuCode==null){
                    k.push(j);
                }
                if(data.successList[i].spuCode!=null){
                    u.push(j);
                }
                if(data.successList[i].skuCode!=null){
                    o.push(j);
                }
            };

            var q=u.length+o.length;
            if(data.failSpuId.length == 0 && data.failSkuId.length == 0){
                if($('.current').text()=='适用商品'){
                    $('#applNumber').html(data.successList.length);
                }
                if($('.current').text()=='排除商品'){
                    $('#removeNumber').html(data.successList.length);
                }
                if(data.successList.length == 0){
                    $.Huimodalalert('导入的表中没有商品数据,请检查数据表!',2000);
                }else{
                    $.Huimodalalert('成功导入全部商品',2000);
                }
            }
            else if(data.failSpuId.length != 0 && data.failSkuId.length != 0){
                console.log(123)
                for(var i=0;i<data.failSpuId.length;i++){
                    failSpu.push(data.failSpuId[i]);
                };
                for(var i=0;i<data.failSkuId.length;i++){
                    failSku.push(data.failSkuId[i]);
                };
                if($('.current').text()=='适用商品'){
                    $('#applNumber').html(data.successList.length);
                }
                if($('.current').text()=='排除商品'){
                    $('#removeNumber').html(data.successList.length);
                }
                $.Huimodalalert('成功导入'+q+'条商品！第{'+failSpu+'}行SPU编码和第{'+failSku+'}行SKU编码的商品:不存在!',3000);
            }
            else if(data.failSpuId.length != 0 && data.failSkuId.length == 0){
                console.log(456)
                for(var i=0;i<data.failSpuId.length;i++){
                    failSpu.push(data.failSpuId[i]);
                };
                if($('.current').text()=='适用商品'){
                    $('#applNumber').html(data.successList.length);
                }
                if($('.current').text()=='排除商品'){
                    $('#removeNumber').html(data.successList.length);
                }
                $.Huimodalalert('成功导入'+q+'条商品！第{'+failSpu+'}行SPU编码的商品:不存在!',3000);
            }
            else if(data.failSpuId.length == 0 && data.failSkuId.length != 0){
                console.log(789)
                for(var i=0;i<data.failSkuId.length;i++){
                    failSku.push(data.failSkuId[i]);
                };
                if($('.current').text()=='适用商品'){
                    $('#applNumber').html(data.successList.length);
                }
                if($('.current').text()=='排除商品'){
                    $('#removeNumber').html(data.successList.length);
                }
                $.Huimodalalert('成功导入'+q+'条商品！第{'+failSku+'}行SKU编码的商品:不存在!',3000);
            }
        }
    });
}


function upLoadFile() {
    $("#fileUp").trigger('click');
}
function getNum(Val){
    console.log(Val);

}
var map1={};
var map2={};
var map3=[];
var map4=[];
//一级选中的code
let bb = new Set();
aa = []
//二级选中的code
let bb1 = new Set();
aa1 = []
//三级选中的code
let bb2 = new Set();
aa2 = []
function pageShow() {
    var customerId = sessionStorage.getItem("customerid")
    var warehouseId = sessionStorage.getItem("id")

    $.ajax({
        url: root.dockingplatform.queryWarehouseCityMap,
        // 告诉jQuery不要去处理发送的数据
        // 告诉jQuery不要去设置Content-Type请求头
        //contentType : false,
        cache: false,
        type: "POST",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            customerId: customerId,
            warehouseId: warehouseId
        }),
        success: function (data) {
            console.log(data);
            //回显
            if (data.errorCode == "0" && data.data != null) {
                // $("#dcName").val(data.data.saleAreaId)
                var result = data
                var anna = result.data.warehouseList[0].warehouseId
                console.log(anna);
                $("#dcName").val(anna);
                for (var j = 0; j < result.data.warehouseList[0].warehouseCoverAddress.length; j++) {
                    var Val = result.data.warehouseList[0].warehouseCoverAddress[j].code
                    map1[Val]={};
                    //二级数组集合
                    var erjiObj = {};
                    for(var i = 0;i<result.data.warehouseList[0].warehouseCoverAddress[j].secondAddressLibrary.length;i++){
                        //每次创建一个二级数组对象
                        var sanjishuzu = [];
                        for(var k = 0;k<result.data.warehouseList[0].warehouseCoverAddress[j].secondAddressLibrary[i].thirdAddressLibrary.length;k++){
                            bb2.add(result.data.warehouseList[0].warehouseCoverAddress[j].secondAddressLibrary[i].thirdAddressLibrary[k].code)
                            sanjishuzu.push(result.data.warehouseList[0].warehouseCoverAddress[j].secondAddressLibrary[i].thirdAddressLibrary[k].code);
                        }
                        erjiObj[result.data.warehouseList[0].warehouseCoverAddress[j].secondAddressLibrary[i].code] = sanjishuzu;
                        bb1.add(result.data.warehouseList[0].warehouseCoverAddress[j].secondAddressLibrary[i].code)
                    }
                    map1[Val]=erjiObj;
                    bb.add(result.data.warehouseList[0].warehouseCoverAddress[j].code)
                }
                for(let val of bb.values()){
                    erji(val)
                    aa.push(val)
                }
                for(let val of bb1.values()){
                    sanji(val)
                    aa1.push(val)
                }
                for(let val of bb2.values()){
                    aa2.push(val)
                }

                aa
                aa1
                aa2
     goods_listCategory1(1)
            }
        }
    });
}



function erji(parentId) {


        oldparentId=parentId;
        var user_data = {
            parentCode: parentId
        }
        var succCallBack = function (data, status, response) {
            for (var i = 0; i < data.list.length; i++) {
                mapList.put(data.list[i].code, data.list[i]);
            }
        };
        return web.doAjax(root.publics.getLowerAddress, 'post', user_data, succCallBack);
}

function sanji(parentId) {

    oldparentId=parentId;
    var user_data = {
        parentCode: parentId
    }
    var succCallBack = function (data, status, response) {
        for (var i = 0; i < data.list.length; i++) {
            mapList1.put(data.list[i].code, data.list[i]);
        }

    };
    return web.doAjax(root.publics.getLowerAddress, 'post', user_data, succCallBack);
}


var firstLevel = [];
var secondLevel = [];
var thirdLevel = [];
var secondLevelSelect = [];
var first = [];
var second = [];
var third = [];
var thirdVal = [];
var selectall = 1;
var length2=0;
var thirdToFirst=[];
var selectall = 1;

//全选
$("#selectAll").click(function(){
    var Ids = 0;
    first = [];
    if(selectall%2==1){
        $("input[name='classification01']").each(function(){
            $(this).prop("checked",true);
            Ids=parseInt(this.id);
            first.push(Ids);
            map1[this.id]={};
        });
        $("#classDiv2").css({
            display: "none"
        });
        $(".removeEl2").remove();
        $("#classDiv3").css({
            display: "none"
        });
        selectall++;
    }
    else{
        $("input[name='classification01']").each(function(){
            $(this).prop("checked",false);
        });
        $("input[name='classification02']").each(function(){
            $(this).prop("checked",false);
        });
        $("input[name='classification03']").each(function(){
            $(this).prop("checked",false);
        });
        selectall++;
        firstLevel=[];
        secondLevel=[];
        thirdLevel=[];
        map1={};
    }
});

//重置
$('#selectReset').click(function () {

    secondLevelSelect = [];
    second = [];
    third = [];
    thirdVal = [];
    oldparentId = [];
    c=[];
    oldparentid = 0;
    $("#classDiv2").css({
        display: "none"
    });
    $(".removeEl2").remove();
    $("#classDiv3").css({
        display: "none"
    });
    $(".removeEl3").remove();
    $("input[name='classification01']").each(function(){
        $(this).prop("checked",false);
    });
    $("input[name='classification02']").each(function(){
        $(this).prop("checked",false);
    });
    $("input[name='classification03']").each(function(){
        $(this).prop("checked",false);
    });
    $("input[name='applRange']").each(function(){
        $(this).prop("checked",false);
    });
    $("input[name='applCate']").each(function(){
        $(this).prop("checked",false);
    });


    // map.put("c","cccccccccccccc");
    // map.remove("b");
});
function makeMap(){
    firstLevel = [];
    for(key1 in map1){
        thirdToFirst=[];
        var lll=0;
        for(var i in map1[key1]){
            lll++
        }
        if(lll==0){
            firstLevel.push(key1);
        }
        for(key2 in map1[key1]){
            cateThird(key1,key2);
            cateSecond(key1,key2);
        }
        // console.log(map1);
        // console.log({"1":firstLevel, "2":secondLevel, "3":thirdLevel})

    }
    console.log({"1":firstLevel, "2":secondLevel, "3":thirdLevel})
    /*for(var i=0;i< firstLevel.length;i++){
        firstLevel[i]=parseInt(firstLevel[i])
    }*/
}
// 判断一级二级关系
function cateSecond(key1,key2){

    $.ajax({
        url: root.publics.getLowerAddress,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        async:false,
        // contentType: "application/json",
        data: {
            parentCode: key1,
        },
        success: function (data) {
            console.log("aaaaaaaaaaaaa"+data.toString())
            var length=0;
            for(var i in map1[key1]){
                length++
            }
            if(length==data.list.length) {
                if(thirdToFirst.length==0&&$.inArray(key1,firstLevel)==-1){
                    firstLevel.push(key1);
                }
                else if(thirdToFirst.length!=0){
                    if($.inArray(key2,secondLevel)==-1){
                    }
                }
            }
            else if(length==0){
                firstLevel.push(key1);
            }
            else {
                if ($.inArray(key2, secondLevel) == -1) {
                    secondLevel.push(key2);
                }
            }
            //判断二级三级关系
            $.ajax({
                url: root.publics.getLowerAddress,
                cache: false,  //禁用缓存
                type: "POST",
                dataType: 'json',
                async:false,
                // contentType: "application/json",
                data: {
                    parentCode: key2,
                },
                success: function (data) {
                    if(data.list.length!=map1[key1][key2].length&&map1[key1][key2].length!=0)
                    {
                        secondLevel.remove(key2);
                    }
                },
                error: function () {
                    console.log('失败')
                }
            })
        },
        error: function () {
            console.log('失败')
        }
    })
}


// 判断一级三级关系
function cateThird(key1,key2){
    $.ajax({
        url: root.publics.getLowerAddress,
        cache: false,  //禁用缓存
        type: "POST",
        dataType: 'json',
        async:false,
        // contentType: "application/json",
        data: {
            parentCode: key2,
        },
        success: function (data) {
            if(map1[key1][key2].length!=0&&map1[key1][key2].length!=data.list.length)
            {
                thirdToFirst=thirdToFirst.concat(map1[key1][key2]);
                for(var i=0;i<map1[key1][key2].length;i++){
                    if($.inArray(map1[key1][key2][i],thirdLevel==-1)){
                        thirdLevel.push(map1[key1][key2][i])
                    }
                }
            }
        },
        error: function () {
            console.log('失败')
        }
    })
}


//数组删除某个元素
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
//字符串以什么结尾
String.prototype.endWith = function (endStr) {
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d);
};


var firstlength=0;
function goods_listCategory1(classNum) {

    var user_data = {
        level: 101
    }
    var succCallBack = function (data, status, response) {
        firstlength=data.list.length;
        if (data.list.length == 0) {
            $("#classSet1").append('<li class="clearfix pl-10 mb-5">无数据</li>');
        }
        else {
            for (var i = 0; i < data.list.length; i++) {
                var categoryId = data.list[i].code;
                if($.inArray(parseInt(categoryId),aa)!=-1){
                    $("#classSet1").append('<li class="clearfix pl-10 mb-5"><div class="f-l pd-5">' +
                        '<input id="' + data.list[i].code + '" onclick="nextbox1(this,'+data.list[i].code+')" name="classification01" type="checkbox"  checked="checked" value="' + data.list[i].code + '" class="checkbox" />' +
                        '<label class="pl-10"  onclick="goods_listCategory2(2,' +data.list[i].code + ',this)">' + data.list[i].code + ' ' + data.list[i].name + '</label></div>' +
                        '<div class="f-r"><a onclick="firstClassAdd(\'#firstClassInp2\',2,1,' + data.list[i].code + ',' + data.list[i].code + ')" ></a>' +
                        '<a href="##" onclick="eidtInpShow(\'#firstClassInp1\',\'#addLabel1\',' + data.list[i].code + ',\'.firstClassId1\',\'' + data.list[i].name + '\',' + data.list[i].code + ')" "></a>' +
                        '<a href="##" onclick="deleteGoodsClass(' + data.list[i].code + ')"></a></div></li>')
                }else{
                    $("#classSet1").append('<li class="clearfix pl-10 mb-5"><div class="f-l pd-5">' +
                        '<input id="' + data.list[i].code + '" onclick="nextbox1(this,'+data.list[i].code+')" name="classification01" type="checkbox" value="' + data.list[i].code + '" class="checkbox" />' +
                        '<label class="pl-10"  onclick="goods_listCategory2(2,' +data.list[i].code + ',this)">' + data.list[i].code + ' ' + data.list[i].name + '</label></div>' +
                        '<div class="f-r"><a onclick="firstClassAdd(\'#firstClassInp2\',2,1,' + data.list[i].code + ',' + data.list[i].code + ')" ></a>' +
                        '<a href="##" onclick="eidtInpShow(\'#firstClassInp1\',\'#addLabel1\',' + data.list[i].code + ',\'.firstClassId1\',\'' + data.list[i].name + '\',' + data.list[i].code + ')" "></a>' +
                        '<a href="##" onclick="deleteGoodsClass(' + data.list[i].code + ')"></a></div></li>')
                }
            }
            firstLevel=data
        }
    };
    return web.doAjax(root.publics.getLowerAddress, 'post', user_data, succCallBack);
}
function nextbox1(that,valCode) {
    var Val = parseInt(that.value);
    if(that.checked){
        flag = 1;
        map1[Val]={};
    }
    else{
        flag = 0;
        $("#classDiv2").css({
            display: "none"
        });
        $("#classDiv3").css({
            display: "none"
        });
        delete map1[Val];
    }
    goods_listCategory2(2,Val,that.nextElementSibling,1)//渲染二级类
}

var oldparentId=0;
function goods_listCategory2(classNum, parentId, e, bol) {
    if(e.previousElementSibling.checked){
        var checkbox = e.previousElementSibling;
        oldparentId=parentId;
        $(".removeEl2").remove();
        $("#classDiv2").css({
            display: "block"
        });
        $("#classDiv3").css({
            display: "none"
        });
        var user_data = {
            parentCode: parentId
        }
        var succCallBack = function (data, status, response) {
            if (data.list.length == 0) {
                $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5">无数据</li>');
            }
            else {
                for (var i = 0; i < data.list.length; i++) {
                    var categoryId = data.list[i].code;
                    if(checkbox.checked){
                        if($.inArray(parseInt(categoryId),second)!=-1){
                            $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"><div class="f-l pd-5"><input onclick="nextbox2(this,'+data.list[i].code+','+parentId+')"  name="classification02" type="checkbox" value="' + data.list[i].code + '"  class="" /><label class="pl-10 secondlevel" onclick="goods_listCategory3(3,' + data.list[i].code + ','+parentId+',this)">' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')
                        }
                        else {
                            if($.inArray(parseInt(categoryId),aa1)!=-1 || flag == 1){
                                aa1.push(parseInt(categoryId));
                                $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox2(this,'+data.list[i].code+','+parentId+')" name="classification02" type="checkbox" value="' + data.list[i].code + '" checked="checked" class="" /><label class="pl-10 secondlevel" onclick="goods_listCategory3(3,' + data.list[i].code + ','+parentId+',this)" >' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')
                                mapList.put(data.list[i].code,data.list[i]);
                            }else{
                                second.push(parseInt(categoryId));
                                $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"><div class="f-l pd-5"><input onclick="nextbox2(this,'+data.list[i].code+','+parentId+')"  name="classification02" type="checkbox" value="' + data.list[i].code + '"  class="" /><label class="pl-10 secondlevel" onclick="goods_listCategory3(3,' + data.list[i].code + ','+parentId+',this)">' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')
                            }

                        //     $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox2(this,'+data.list[i].code+','+parentId+')" name="classification02" type="checkbox" value="' + data.list[i].code + '" checked="checked" class="" /><label class="pl-10 secondlevel" onclick="goods_listCategory3(3,' + data.list[i].code + ','+parentId+',this)" >' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')
                        }
                        $("input[name='classification02']").each(function(){
                            if(this.checked){
                                map2[this.value]=[];
                            }
                        });
                        if(bol == 1){
                            map1[parentId]=map2;
                            map2={};
                        }
                        map2={};
                    }
                    else{
                        $("#classSet2").append('<li class="removeEl2 clearfix pl-10 mb-5"><div class="f-l pd-5"><input onclick="nextbox2(this,'+data.list[i].code+','+parentId+')"  name="classification02" type="checkbox" value="' + data.list[i].code + '"  class="" /><label class="pl-10 secondlevel" onclick="goods_listCategory3(3,' + data.list[i].code + ','+parentId+',this)">' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')
                    }
                }
                if(bol == 1) {
                    $("input:checkbox[name=classification02]:checked").each(function(){
                        var b =$(this).val()
                        aaaa(parentId,b);
                    });
                }
                flag = 0;
            }
        };
        return web.doAjax(root.publics.getLowerAddress, 'post', user_data, succCallBack);
    }
}

function aaaa(parentId, grandParentId) {
    var user_data = {
        parentCode: grandParentId
    }
    var succCallBack = function (data, status, response) {
        for (var i = 0; i < data.list.length; i++) {
            map3.push(data.list[i].code);
            aa2.push(parseInt(data.list[i].code));
            mapList1.put(data.list[i].code,data.list[i]);
        }
        map1[parentId][grandParentId] = map3;
        map3 = [];
    }
    return web.doAjax(root.publics.getLowerAddress, 'post', user_data, succCallBack);
}



var oldparentIds = [];
function nextbox2(that,valCode,parentId) {
    var a=0;
    var b=[];
    var Val = parseInt(that.value)
    /* if($.inArray(parentId,oldparentIds)==-1){
         map2 = new Map();
     }*/
    if(that.checked){
        flag2 = 1;
        second.remove(Val)
        map1[parentId][Val]=[];
        $("input[name='classification02']").each(function(){
            if(this.checked){
                a++
            }
        });
        var levelsecond = document.getElementsByName('classification02').length;
        aa1.push(parseInt(valCode));
    }
    else{
        flag2 = 0;
        second.push(Val)
        delete map1[parentId][Val];
        $("#classDiv3").css({
            display: "none"
        });
        $("input[name='classification02']").each(function(){
            if(this.checked){
                b.push(parseInt(this.value));
            }
        });
        b=[];
    }
    goods_listCategory3(3, valCode, parentId, that.nextElementSibling)
}
function goods_listCategory3(classNum, parentId, grandParentId, e) {
    var checkbox = e.previousElementSibling;

    if(checkbox.checked) {
        $("#classDiv3").css({
            display: "block"
        });
        $(".removeEl3").remove();
        var user_data = {
            parentCode: parentId
        }
        var succCallBack = function (data, status, response) {
            if (data.list.length == 0) {
                $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5">无数据</li>');
            }
            else {
                for (var i = 0; i < data.list.length; i++) {
                    var categoryId = data.list[i].code.toString()
                    if (checkbox.checked) {
                        if ($.inArray(parseInt(categoryId), third) != -1) {
                            $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox3(this,' + data.list[i].code + ',' + parentId + ',' + grandParentId + ')"  name="classification03" type="checkbox" value="' + data.list[i].code + '"  class="" /><label class="pl-10" onclick="goods_listCategory4(4,' + data.list[i].code + ',' + grandParentId + ')">' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')
                        }
                        else {
                            if($.inArray(parseInt(categoryId),aa2)!=-1 || flag2 == 1){
                                aa2.push(parseInt(categoryId));
                                $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox3(this,' + data.list[i].code + ',' + parentId + ',' + grandParentId + ')"  name="classification03" type="checkbox" value="' + data.list[i].code + '" checked="checked" class="checkbox" /><label class="pl-10" onclick="goods_listCategory4(4,' + data.list[i].code + ',' + grandParentId + ')">' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')

                            }else{
                                third.push(parseInt(categoryId));
                                $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox3(this,' + data.list[i].code + ',' + parentId + ',' + grandParentId + ')"  name="classification03" type="checkbox" value="' + data.list[i].code + '"  class="" /><label class="pl-10" onclick="goods_listCategory4(4,' + data.list[i].code + ',' + grandParentId + ')">' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')

                            }
                        //     mapList1.put(data.list[i].code,data.list[i]);
                        //     $("#classSet3").append('<li class="removeEl3 clearfix pl-10 mb-5"><div class="f-l pd-5" ><input onclick="nextbox3(this,' + data.list[i].code + ',' + parentId + ',' + grandParentId + ')"  name="classification03" type="checkbox" value="' + data.list[i].code + '" checked="checked" class="checkbox" /><label class="pl-10" onclick="goods_listCategory4(4,' + data.list[i].code + ',' + grandParentId + ')">' + data.list[i].code + ' ' + data.list[i].name + '</label></div></li>')
                        }
                    }
                }
                $("input[name='classification03']").each(function () {
                    if (this.checked) {
                        map3.push(this.value);
                    }
                });
                map1[grandParentId][parentId] = map3;
                map3 = [];
                $("input:checkbox[name=classification03]:checked").each(function(){
                    var b =$(this).val()
                    for (var i = 0; i < data.list.length; i++) {
                        if(data.list[i].code == b ){
                            mapList1.put(b,data.list[i]);
                        }
                    }
                });
                flag2 = 0;
            }
        }
        return web.doAjax(root.publics.getLowerAddress, 'post', user_data, succCallBack);
    }
}

function nextbox3(that,valCode, parentId, grandParentId) {
    var c=[]
    var thirds = 0;
    var seconds = 0;
    if(that.checked){
        $("input[name='classification03']").each(function(){
            if(this.checked){
                map3.push(this.value);
                thirds++;
            }
        });
        $("input[name='classification02']").each(function(){
            if(this.checked){
                seconds++;
            }
        });
        var levelthird = document.getElementsByName('classification03').length;
        var levelsecond = document.getElementsByName('classification02').length;

        var k=0;
        for(key in map1[grandParentId][parentId]){
            k++
        }
        map1[grandParentId][parentId]=map3;
        if(seconds==k){
            map1[grandParentId][parentId]=[];
        }
        map3=[];
        third.remove(that.value);
        aa2.push(parseInt(valCode));
    }
    else{
        third.push(parseInt(that.value))
        $("input[name='classification03']").each(function(){
            if(this.checked){
                map3.push(this.value);
                c.push(parseInt(this.value))
            }
        });
        c=[];
        map1[grandParentId][parentId]=map3;
        map3=[];
        /*thirdLevel.remove(that.value)*/
    }
    var thirdArray=[];


}


//保存提交
function waySave() {
    var warehouseCode = $('#dcName option:selected').val();
    var warehouseName = $('#dcName option:selected').text();
    console.log(warehouseCode)
    console.log(warehouseName)
    firstLevel3 = [];
    secondLevel3 = [];
    thirdLevel3 = [];
    var firstLevel1 = []
    var secondLevel1 = []
    var thirdLevel1 = []
    // makeMap();
    //获取选中地址
    //获取一级地址
    //对比获取一级地址
    $("input:checkbox[name=classification01]:checked").each(function(
    ){
        var a = $(this).val()
        for (var i = 0; i  < firstLevel.list.length; i++) {
            if(firstLevel.list[i].code == a){
                firstLevel1.push(firstLevel.list[i])
            }
        }
    });
    for(var i=0;i<firstLevel1.length;i++){
        var voi = {};
        voi.code = firstLevel1[i].code
        voi.name = firstLevel1[i].name
        voi.level = firstLevel1[i].level
        firstLevel3.push(voi)
    }
    if(firstLevel3.length == 0) {
        $.Huimodalalert('一级类地址必选', 2000);
        return false;
    }
    //循环二级地址

    b = []
    for(var key in map1){
        for(var key1 in map1[key]){
            b.push(key1)
        }
    }

    for(var key in mapList.map){
        secondLevel.push(mapList.map[key])
    }
    //对比获取二级地址
    for(var key in b){
        console.log('>>>>>>>>>>FSDFSD'+secondLevel.length)
        for(var i=0; i<secondLevel.length;i++){
            console.log('>>>>>>>>>>>>>>>>:'+i)
            if(parseInt(secondLevel[i].code) == parseInt(b[key])){
                secondLevel1.push(secondLevel[i])
                break;
            }
        }
    }
    for(var i=0;i<secondLevel1.length;i++){
        var voi = {};
        voi.code = secondLevel1[i].code
        voi.name = secondLevel1[i].name
        voi.level = secondLevel1[i].level
        voi.parentCode = secondLevel1[i].parent_code
        secondLevel3.push(voi)
    }
    if(secondLevel3.length == 0) {
        $.Huimodalalert('二级类地址必选', 2000);
        return false;
    }
    //循环三级地址
    let k = new Set();
    for(var key in map1){
        for(var key1 in map1[key]){
            var erji = map1[key];
            Object.keys(erji).forEach(function(key){
                if(null != erji[key] && erji[key].length > 0){
                    var sanji = erji[key]
                    for(var w = 0 ; w<sanji.length;w++){
                        k.add(sanji[w])
                    }
                }
            });
        }
    }

    for(var key in mapList1.map){
        console.log(mapList1.map[key])
        thirdLevel.push(mapList1.map[key])
    }
    for(let val of k.values()){
        for(var i=0;i<thirdLevel.length;i++){
            if(thirdLevel[i].code == val){
                thirdLevel1.push(thirdLevel[i])
            }
        }
    }
    for(var i=0;i<thirdLevel1.length;i++){
        var voi = {};
        voi.code = thirdLevel1[i].code
        voi.name = thirdLevel1[i].name
        voi.level = thirdLevel1[i].level
        voi.parentCode = thirdLevel1[i].parent_code
        thirdLevel3.push(voi)
    }
    if(thirdLevel3.length == 0) {
        $.Huimodalalert('三级类地址必选', 2000);
        return false;
    }











    var loginData=JSON.parse(web.readCookie("loginData"));
    var a = sessionStorage.getItem("customerid")

    var datas = {
        customerId : sessionStorage.getItem("customerid"),
        createdBy : loginData.user.user_ID,
        warehouseId: warehouseCode,
        warehouseName: warehouseName,
        addrList:{
            "1":firstLevel3,
            "2":secondLevel3,
            "3":thirdLevel3
        },
    }
    console.log(datas);
    $.ajax({
        url: root.dockingplatform.saveWarehouseCityMap,
        cache: false, //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            customerId : sessionStorage.getItem("customerid"),
            // createdBy : loginData.user.user_ID,
            warehouseId: warehouseCode,
            warehouseName: warehouseName,
            addrList: {
                firstAddrList: firstLevel3,
                secondAddrList: secondLevel3,
                thirdAddrList: thirdLevel3
            }
        }),
        success: function(result){
            if(result.errorCode == 0){
                layer.msg("设置成功", {
                    icon: 1,
                    time: 1000,
                    end: function () {
                        var index =  parent.location.reload();
                        parent.layer.close(index);
                    }
                });
            }else{
                thirdLevel = []
                second = []
                layer.msg(result.msg, {icon: 5,time:2000});
                parent.layer.close(index);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest);
            //alert(XMLHttpRequest);
        }
    });
}



$("#wayCancel").click(function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})




function getAllWare() { //获取所有的发货仓
    var sel = document.getElementById("dcName");
    $.ajax({
        url: 'https://'+ window.location.host +'/api/admin/abaseservice/area/getAllWarehouse',
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        async: false,//优先运行
        data: {},
        success: function (obj) {
            for (var i = 0; i < obj.data.length; i++) {
                var option = new Option(obj.data[i].warehouse_name, obj.data[i].warehouse_code);
                sel.options.add(option)
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //console.log(XMLHttpRequest);
            alert(XMLHttpRequest);
        }
    });
}

function check(){
    console.log(firstLevel);
    console.log(secondLevel);
    console.log(thirdLevel);

    console.log("range="+range);

    console.log("firstlength="+firstlength);
    console.log("firstLevel.length="+firstLevel.length);

}

